package io.mvvm.ws.handler;

import io.mvvm.ws.WebSocketChannelHolder;
import io.mvvm.ws.entity.RequestInfo;
import io.mvvm.ws.entity.ResponseInfo;
import io.mvvm.ws.chain.MessageHandlerChain;
import io.mvvm.ws.utils.SendMessageUtil;
import io.netty.channel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.InetSocketAddress;

/**
 * @program: Netty
 * @description: 消息处理器
 * @author: 潘
 * @create: 2021-04-21 19:26
 **/
@Component
@ChannelHandler.Sharable
public class WebSocketMessageHandler extends SimpleChannelInboundHandler<RequestInfo> {

    public static final String HANDLER_NAME = "WebSocketMessageHandler";

    private static Logger logger = LoggerFactory.getLogger(WebSocketMessageHandler.class);

    @Resource
    private MessageHandlerChain messageHandlerChain;

    /**
     * 收到消息时调用
     * @param ctx
     * @param request
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RequestInfo request) throws Exception {
        String userName = ctx.channel().attr(WebSocketAuthHandler.key).get();
        request.setUserId(userName);
        ResponseInfo response = messageHandlerChain.init().start(request, ctx);
        SendMessageUtil.send(userName, response);
//        ctx.fireChannelRead(response);
    }

    /**
     * 客户端与服务端断开连接时调用
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        String uid = WebSocketChannelHolder.removeChannel(ctx.channel());
    }

//    @Override
//    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
//        if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {
//
//            String userName = ctx.channel().attr(WebSocketAuthHandler.key).get();
//
//        }else if (evt instanceof IdleStateEvent) {
//            // 2*4+1 s内读空闲时，关掉连接，表示客户端不可见了
//            IdleStateEvent evnet = (IdleStateEvent) evt;
//            if (evnet.state().equals(IdleState.READER_IDLE)) {
//                ctx.close();
//            }
//        } else {
//            super.userEventTriggered(ctx, evt);
//        }
//    }

    /**
     * 获取客户端IP
     * @param ctx
     * @return
     */
    private String getChannelIp(ChannelHandlerContext ctx) {
        InetSocketAddress ipSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        return ipSocket.getAddress().getHostAddress();
    }


}
